from django.db.models import signals
from models import OnModelChange
from django.contrib.contenttypes.models import ContentType

from staticgenerator import quick_delete, quick_publish
    
def on_model_change(sender, instance, **kwargs):
    content_type = ContentType.objects.get_for_model(sender)
    for trigger in OnModelChange.objects.filter(content_type=content_type):
        urls = trigger.get_urls(instance)
        if trigger.delete:
            quick_delete(*urls)
        if trigger.publish:
            quick_publish(*urls)

def update_listener(instance, created, **kwargs):
    if created:
        signals.post_save.connect(on_model_change, instance.content_type.model_class())
        signals.post_delete.connect(on_model_change, instance.content_type.model_class())

def remove_listener(instance, **kwargs):
    signals.post_save.disconnect(on_model_change, instance.content_type)
    signals.post_delete.disconnect(on_model_change, instance.content_type)

signals.post_save.connect(update_listener, OnModelChange)
signals.post_delete.connect(remove_listener, OnModelChange)

#initializing signals defined in db
for rule in OnModelChange.objects.all():
    update_listener(rule, True)